import { FC, PropsWithChildren, useEffect, UIEvent } from "react";
import {
  PhoneOutlined,
  HistoryOutlined,
  SkinOutlined
} from "@ant-design/icons";
import SlideMove from "@/components/SlideMove";
import SlideList from "@/components/SlideList";
import ChatItem from "../../commponents/ChatItem";
import friendsSocketApiFunc from "@/api/socket/socketFunc/friends.ts";
import { useRef, useState } from "react";
import {
  GetHistoryMessage,
  FriendMessage,
  BaseMessage,
  setMessageRead,
  SendMessage,
  RecallMessage
} from "@/api/xhr/message";
import { Button, message as antdMessage } from "antd";
import { getStoreItem } from "@/util/storage";
import { useParams } from "react-router-dom";
import { Input } from "antd";
import EmojiPicker from "../../commponents/EmojiPicker";
import SoundManager from "@/util/sound";
import VoiceCall from "../../commponents/VoiceCall";
import socketInstance from "@/api/socket";
import { MessageType } from "@/api/type/messageType";
import CallSoundManager from "@/util/callSound";
import ChatHistory from "../../commponents/ChatHistory";
import ThemeSelector from "../../commponents/ThemeSelector";
import { ChatTheme } from "@/styles/themes";
import { formatFullDateTime } from "@/util/index";

const { TextArea } = Input;

type TypeProps = {
  type: string;
};

// 对方信息接口
interface OpponentInfo {
  id: number;
  name: string;
  avatar: string;
}

const MessageBody: FC<PropsWithChildren<TypeProps>> = ({ type }) => {
  const userinfo = JSON.parse(getStoreItem("userinfo"));
  const userId = userinfo?.id;
  const params = useParams();
  const [messageList, setMessageList] = useState<
    (
      | BaseMessage<FriendMessage & { isme: boolean }>
      | (BaseMessage<null> & { isme: boolean })
    )[]
  >([]);
  const elRef = useRef<HTMLDivElement>(null); // 获取元素
  const elRefs = useRef<HTMLUListElement>(null); // 获取元素
  const sideRef = useRef<HTMLDivElement>(null); // 获取元素
  const [isLoading, setisLoading] = useState(2);
  const [viewingHistory, setViewingHistory] = useState(false);
  const domRef = useRef<{ slideBottom: () => void }>(null);
  const [voiceCallVisible, setVoiceCallVisible] = useState(false);
  const [incomingCall, setIncomingCall] = useState(false);
  // 提取对方信息
  const [opponentInfo, setOpponentInfo] = useState<OpponentInfo | null>(null);
  // 聊天历史记录弹框
  const [historyVisible, setHistoryVisible] = useState(false);
  
  // 使用ref来存储通话开始时间，以避免状态更新延迟问题
  const callStartTimeRef = useRef<number | null>(null);
  // 保留state用于可能的UI更新，尽管当前没有直接使用
  const [, setCallStartTimeState] = useState<number | null>(null);
  const [themeSettings, setThemeSettings] = useState<ChatTheme | null>(null);
  const [themeVisible, setThemeVisible] = useState<boolean>(false);


  // 获取对方信息
  useEffect(() => {
    if (messageList.length > 0 && !messageList[0].isme && messageList[0].messageSendType !== 0) {
      const firstMessage = messageList[0];
      setOpponentInfo({
        id: firstMessage.id,
        name: firstMessage.name || "用户",
        avatar: firstMessage.avatar || ""
      });
    }
  }, [messageList]);

  const handleScroll = (e: UIEvent<HTMLDivElement>) => {
    const scrollTop = (e.target as HTMLDivElement).scrollTop;
    if (
      scrollTop <
      (e.target as HTMLDivElement).scrollHeight -
        (e.target as HTMLDivElement).clientHeight -
        100
    ) {
      setViewingHistory(true);
    } else {
      setViewingHistory(false);
    }
  };

  async function Refresh() {
    if (messageList.length === 0) {
      await GetMessage();
      return;
    }

    setViewingHistory(true);

    const messageId = messageList[0].id
      ? messageList[0].messageId
      : messageList[1]?.messageId;

    if (messageId) {
      await GetMessage(messageId);
    }
  }

  async function GetMessage(startId?: number) {
    setisLoading(1);
    const data = params.contactId?.split("-");
    const id = data && Number(data[1]);
    const res = await GetHistoryMessage({
      messageId: id!,
      messageSize: 10,
      startId,
      type: type as "group" | "friend",
      userId: userId
    });
    if (res.statusCode == 200) {
      const existingMessageIds = new Set(
        messageList.map(
          msg => `${msg.id}-${msg.content}-${new Date(msg.createdAt).getTime()}`
        )
      );

      const newMessages = res.data.list
        .filter(
          item =>
            !existingMessageIds.has(
              `${item.id}-${item.content}-${new Date(item.createdAt).getTime()}`
            ) && 
            (item.messageStatus !== 0) // 过滤掉 messageStatus 为 0 的消息
        )
        .map(item => {
          return {
            ...item,
            isme: item?.id == userId
          };
        });

      // 对合并后的消息列表进行排序
      const mergedMessages = [...newMessages, ...messageList];
      mergedMessages.sort((a, b) => {
        // 确保 messageId 存在且为数字类型进行比较
        const aMessageId = Number(a.messageId);
        const bMessageId = Number(b.messageId);

        if (isNaN(aMessageId) || isNaN(bMessageId)) {
          // 如果messageId无效，则保持原有顺序或根据创建时间排序
          return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
        }
        return aMessageId - bMessageId;
      });

      setMessageList(mergedMessages);

      // 如果有新消息且第一条不是自己发的，更新对方信息
      if (newMessages.length > 0 && !newMessages[0].isme && newMessages[0].messageSendType !== 0) {
        const firstMessage = newMessages[0];
        setOpponentInfo({
          id: firstMessage.id,
          name: firstMessage.name || "用户",
          avatar: firstMessage.avatar || ""
        });
      }

      if (
        (res.data.total <= 1 &&
          res.data.list.length === 1 &&
          res.data.list[0].messageSendType === 0) ||
        newMessages.length === 0
      ) {
        setisLoading(3);
      } else {
        setisLoading(2);
      }
    }
  }

  // 添加发送时间系统消息的函数
  const sendTimeMessage = async () => {
    const data = params.contactId?.split("-");
    const id = data && Number(data[1]);
    
    if (!id) return;
    
    // 创建时间提示系统消息
    const timeMessage = formatFullDateTime(new Date());
    
    try {
      // 发送系统消息到服务器
      const res = await SendMessage({
        id: id,
        userId: userId,
        content: timeMessage,
        type: type,
        messageType: "time", // 指定消息类型为time
        messageSendType: 0 // 设置为系统消息
      });
      
      return res.statusCode === 200;
    } catch (error) {
      console.error("发送时间消息失败:", error);
      return false;
    }
  };

  // 修改 handelSendMessage，使用新的 sendTimeMessage 函数发送时间消息
  async function handelSendMessage() {
    const data = params.contactId?.split("-");
    const id = data && Number(data[1]);

    if (!content.trim()) return;

    // 检查时间差，添加时间节点系统消息
    const currentTime = new Date();
    
    // 获取最后一条消息的时间
    let shouldAddTimeMessage = false;
    if (messageList.length > 0) {
      const lastMessage = messageList[messageList.length - 1];
      const lastMessageTime = new Date(lastMessage.createdAt);
      
      // 计算时间差（毫秒）
      const timeDiff = currentTime.getTime() - lastMessageTime.getTime();
      
      // 如果时间差大于10分钟（600000毫秒），添加时间提示
      if (timeDiff > 600000) {
        shouldAddTimeMessage = true;
      }
    } else {
      // 如果是对话的第一条消息，也添加时间提示
      shouldAddTimeMessage = true;
    }
    
    // 如果需要添加时间提示消息
    if (shouldAddTimeMessage) {
      await sendTimeMessage();
    }

    // 发送用户实际输入的消息
    const res = await SendMessage({
      id: id!,
      userId: userId,
      content: content,
      type: type
    });
    
    if (res.statusCode == 200) {
      setcontent("");
      setViewingHistory(false);
      setTimeout(() => {
        domRef.current?.slideBottom();
      }, 100);
    }
  }

  // 修改 handelSocketGetFriendMessage 函数，使用服务器发送时间消息
  const handelSocketGetFriendMessage = (data: BaseMessage<FriendMessage>) => {
    const paramsdata = params.contactId?.split("-");
    const id = paramsdata && Number(paramsdata[1]);
    if (id !== data.messageId) {
      return;
    }
    
    // 过滤掉 messageStatus 为 0 的消息
    if (data.messageStatus === 0) {
      console.log("收到已撤回的消息，不展示:", data);
      return;
    }
    
    setMessageRead({
      messageId: id!,
      type: "friend",
      userId: userId
    });

    const isMyMessage = data?.id == userId;

    // 检查时间差，并发送时间节点系统消息（仅在非自己发送的消息上检查）
    if (!isMyMessage && messageList.length > 0) {
      const lastMessage = messageList[messageList.length - 1];
      const lastMessageTime = new Date(lastMessage.createdAt);
      const currentMessageTime = new Date(data.createdAt);
      
      // 计算时间差（毫秒）
      const timeDiff = currentMessageTime.getTime() - lastMessageTime.getTime();
      
      // 如果时间差大于10分钟（600000毫秒），服务器端发送时间消息
      if (timeDiff > 600000) {
        // 服务器发送时间系统消息
        // 注意：这里不立即发送，因为这是收到对方消息的情况
        // 由于是接收对方消息，所以应该在对方消息之前显示时间消息
        // 这里通过消息的timestamp判断，对方的客户端会自行添加时间消息
        // 当前端显示时已经通过时间戳排序，确保显示顺序正确
      }
    }

    // 播放消息提示音（如果不是自己的消息）
    if (!isMyMessage) {
      console.log("准备播放好友消息提示音");
      // 从消息中获取发送者信息用于通知
      const senderName = data.name || "好友";
      SoundManager.getInstance().playMessageSound(
        false,
        senderName,
        data.content
      );

      // 更新对方信息
      setOpponentInfo({
        id: data.id,
        name: data.name || "用户",
        avatar: data.avatar || ""
      });
    }

    setMessageList(datamessage => {
      return [
        ...datamessage,
        {
          ...data,
          isme: isMyMessage
        }
      ];
    });

    if (isMyMessage || !viewingHistory) {
      setTimeout(() => {
        domRef.current?.slideBottom();
      }, 100);
    }
  };

  // 修改 handelSocketGetgroupMessage 函数，使用服务器发送时间消息
  const handelSocketGetgroupMessage = (data: any) => {
    const paramsdata = params.contactId?.split("-");
    const id = paramsdata && Number(paramsdata[1]);
    if (id !== data.messageId) {
      return;
    }
    
    // 过滤掉 messageStatus 为 0 的消息
    if (data.messageStatus === 0) {
      console.log("收到已撤回的群组消息，不展示:", data);
      return;
    }
    
    setMessageRead({
      messageId: id!,
      type: "group",
      userId: userId
    });

    const isMyMessage = data?.id == userId;

    // 检查时间差，由服务器发送时间节点系统消息（仅在非自己发送的消息上检查）
    if (!isMyMessage && messageList.length > 0) {
      const lastMessage = messageList[messageList.length - 1];
      const lastMessageTime = new Date(lastMessage.createdAt);
      const currentMessageTime = new Date(data.createdAt);
      
      // 计算时间差（毫秒）
      const timeDiff = currentMessageTime.getTime() - lastMessageTime.getTime();
      
      // 如果时间差大于10分钟（600000毫秒），通过服务器发送时间消息
      if (timeDiff > 600000) {
        // 同上，接收他人消息时不需要当前客户端发送时间消息
        // 只需要在发送消息时检查时间差并添加时间消息
      }
    }
    // 播放消息提示音（如果不是自己的消息）
    if (!isMyMessage) {
      console.log("准备播放群组消息提示音");
      // 群组消息可能有额外的字段，如果没有则使用默认值
      const senderName = data.name || "群成员";
      SoundManager.getInstance().playMessageSound(
        false,
        senderName,
        data.content
      );
    }

    setMessageList(datamessage => {
      return [
        ...datamessage,
        {
          ...data,
          isme: isMyMessage
        }
      ];
    });

    if (isMyMessage || !viewingHistory) {
      setTimeout(() => {
        domRef.current?.slideBottom();
      }, 100);
    }
  };
  useEffect(() => {
    if (type == "friend") {
      friendsSocketApiFunc.getFriendMessage = handelSocketGetFriendMessage;
    } else {
      friendsSocketApiFunc.getgroupMessage = handelSocketGetgroupMessage;
    }
    // 添加撤回消息的监听
    friendsSocketApiFunc.recallMessage = handleSocketRecallMessage;
    
    // 添加自定义事件监听，用于从头部组件打开主题设置
    const handleOpenThemeSettings = () => {
      openThemeSettings();
    };
    window.addEventListener("openThemeSettings", handleOpenThemeSettings);
    
    (async function () {
      await GetMessage();
      domRef.current?.slideBottom();
    })();
    return () => {
      if (type == "friend") {
        friendsSocketApiFunc.getFriendMessage = () => {};
      } else {
        friendsSocketApiFunc.getgroupMessage = () => {};
      }
      // 移除撤回消息的监听
      friendsSocketApiFunc.recallMessage = () => {};
      // 移除主题设置事件监听
      window.removeEventListener("openThemeSettings", handleOpenThemeSettings);
    };
  }, []);
  const [content, setcontent] = useState("");

  const handleEmojiSelect = (emoji: string, mappedText: string) => {
    setcontent(prev => prev + mappedText);
  };

  // 语音通话相关
  useEffect(() => {
    const socket = socketInstance.socket;
    
    if (socket) {
      // 监听通话请求
      socket.on(MessageType.VOICECALL_REQUEST, (callData) => {
        if (opponentInfo && callData.from === opponentInfo.id) {
          // 播放来电铃声
          CallSoundManager.getInstance().playRingtone();
          setIncomingCall(true);
          setVoiceCallVisible(true);
        }
      });

      // 监听通话错误
      socket.on("callError", (errorData) => {
        antdMessage.error(errorData.message || "通话请求失败");
        // 停止铃声
        CallSoundManager.getInstance().stopRingtone();
        setVoiceCallVisible(false);
      });
      
      // 监听通话开始
      socket.on(MessageType.VOICECALL_ACCEPT, () => {
        const now = Date.now();
        callStartTimeRef.current = now;
        setCallStartTimeState(now);
      });
      
      // 监听通话结束
      socket.on(MessageType.VOICECALL_HANGUP, () => {
        // 防止重复处理
        if (voiceCallVisible) {
          handleCallEnded();
          setVoiceCallVisible(false);
          setIncomingCall(false);
        }
      });

      return () => {
        socket.off(MessageType.VOICECALL_REQUEST);
        socket.off("callError");
        socket.off(MessageType.VOICECALL_ACCEPT);
        socket.off(MessageType.VOICECALL_HANGUP);
        // 确保清理铃声
        CallSoundManager.getInstance().stopRingtone();
      };
    }
  }, [opponentInfo, antdMessage]);
  // 处理通话结束，保存通话记录
  const handleCallEnded = () => {
    // 停止铃声
    CallSoundManager.getInstance().stopRingtone();
    
    const currentCallTime = callStartTimeRef.current;    
    // 立即清空callStartTimeRef，防止重复处理
    callStartTimeRef.current = null;
    setCallStartTimeState(null); 
    
    // 只有在有通话时间（即通话已连接）的情况下才发送消息
    if (currentCallTime) {
      const callDurationSeconds = Math.floor((Date.now() - currentCallTime) / 1000);
      let callMessage;
      
      if (callDurationSeconds < 60) {
        // 不足一分钟，以秒为单位显示
        callMessage = `通话时长 ${callDurationSeconds} 秒`;
      } else {
        // 超过一分钟，以分钟为单位显示
        const callDurationMinutes = Math.floor(callDurationSeconds / 60);
        callMessage = `通话时长 ${callDurationMinutes} 分钟`;
      }
      // 发送通话记录消息
      sendCallRecord(callMessage);
    }
  };
  
  // 发送通话记录消息
  const sendCallRecord = async (callMessage: string) => {
    const data = params.contactId?.split("-");
    const id = data && Number(data[1]);
    
    if (!id) return;
    
    const res = await SendMessage({
      id: id,
      userId: userId,
      content: callMessage,
      type: type,
      messageType: "call", // 指定消息类型为call
      messageSendType: 0 // 设置为系统消息，不是由任何一方发送的
    });
    
    if (res.statusCode == 200) {
      setViewingHistory(false);
      setTimeout(() => {
        domRef.current?.slideBottom();
      }, 100);
    }
  };

  const startVoiceCall = () => {
    const socket = socketInstance.socket;
    
    if (!socket) {
      antdMessage.error("网络连接已断开，请刷新页面后重试");
      return;
    }
    
    if (!opponentInfo) {
      antdMessage.error("无法获取对方信息，对方暂不在线");
      return;
    }
    
    if (!userinfo) {
      antdMessage.error("登录信息已失效，请重新登录");
      return;
    }
    
    // 检查麦克风权限
    navigator.mediaDevices.getUserMedia({ audio: true })
      .then(() => {
        // 清理上一次通话的开始时间，以防万一
        callStartTimeRef.current = null;
        setCallStartTimeState(null);

        // 发送通话请求
        socket.emit(MessageType.VOICECALL_REQUEST, {
          to: opponentInfo.id,
          from: userinfo.id,
          username: userinfo.userName
        });
        
        // 显示正在呼叫对方的通话界面
        setIncomingCall(false); // 这是主动呼叫，而非来电
        setVoiceCallVisible(true);
        
        antdMessage.info("正在等待对方接受通话...");
      })
      .catch((err) => {
        console.error("麦克风访问错误:", err);
        if (err.name === "NotAllowedError" || err.name === "PermissionDeniedError") {
          antdMessage.error("麦克风权限被拒绝，请允许浏览器访问麦克风");
        } else if (err.name === "NotFoundError" || err.name === "DevicesNotFoundError") {
          antdMessage.error("未检测到麦克风设备，请确认麦克风已连接");
        } else if (err.name === "NotReadableError" || err.name === "TrackStartError") {
          antdMessage.error("麦克风被其他应用占用，请关闭其他使用麦克风的应用");
        } else {
          antdMessage.error(`无法访问麦克风: ${err.message}`);
        }
      });
  };

  const closeVoiceCall = () => {
    // 如果通话可见，说明正在通话或来电，需要发送挂断信号
    if (voiceCallVisible && opponentInfo) {
      const socket = socketInstance.socket;
      if (socket) {
        // 向服务器发送挂断信号
        socket.emit(MessageType.VOICECALL_HANGUP, {
          to: opponentInfo.id,
          from: userId
        });
      }
    }
    
    // 处理通话结束
    handleCallEnded(); // This is the primary path for initiating call end processing
    
    // 隐藏通话界面
    setVoiceCallVisible(false);
    setIncomingCall(false);
  };

  // 打开聊天历史记录
  const openChatHistory = () => {
    setHistoryVisible(true);
  };

  // 关闭聊天历史记录
  const closeChatHistory = () => {
    setHistoryVisible(false);
  };

  // 撤回消息处理
  const handleRecallMessage = async (messageId: string | number) => {
    try {
      console.log("撤回消息", messageId);
      const res = await RecallMessage({
        messageId,
        type: type as "group" | "friend",
        userId: userId
      });
      
      if (res.statusCode === 200) {
        antdMessage.success("消息已撤回");
        
        // 在服务器响应成功后立即从本地移除消息
        setMessageList(prevList => {
          return prevList.filter(item => item.id !== messageId);
        });
      } else {
        console.error("撤回消息失败", res);
        antdMessage.error(res.errorInfo || "撤回消息失败");
      }
    } catch (error) {
      console.error("撤回消息出错:", error);
      antdMessage.error("撤回消息失败");
    }
  };

  // 添加消息撤回的socket监听
  const handleSocketRecallMessage = (data: { messageId: string | number, type: string}) => {
    console.log("收到消息撤回通知:", data, "当前会话ID:");
    if (data.type !== type) return;
    // 更新消息列表，从列表中移除被撤回的消息
    setMessageList(prevList => {
      // 查找消息进行日志记录
      const messageToRemove = prevList.find(item => 
        item.messageId?.toString() == data.messageId.toString()
      );
      console.log(prevList,"messageToRemove");
      if (messageToRemove) {
        console.log("找到要移除的消息:", messageToRemove);
      } else {
        console.log("未找到要移除的消息, 当前消息列表:", prevList);
      }
      
      // 从列表中过滤掉被撤回的消息
      return prevList.filter(item => 
        item.id?.toString() !== data.messageId.toString() && 
        item.messageId?.toString() !== data.messageId.toString()
      );
    });
  };

  // 打开主题设置
  const openThemeSettings = () => {
    setThemeVisible(true);
  };

  // 关闭主题设置
  const closeThemeSettings = () => {
    setThemeVisible(false);
  };

  // 处理主题变更
  const handleThemeChange = (theme: ChatTheme) => {
    setThemeSettings(theme);
  };

  return (
    <div 
      className="h-[calc(100%-3rem)] w-full flex flex-col" 
      ref={elRef} 
      style={{ 
        background: themeSettings?.chatBackground || "white",
        fontFamily: themeSettings?.fontFamily || "inherit"
      }}
    >
      <div className="h-[70%] w-full" ref={sideRef}>
        <SlideList
          loderpos="top"
          Refresh={Refresh}
          isloding={isLoading}
          ref={domRef}
          onScroll={handleScroll}
        >
          <ul className="max-h-96 w-full p-2 px-4" ref={elRefs}>
            {messageList.map(item => {
              // 首先判断是否是通话记录类型的系统消息
              if (item.messageSendType === 0 && item.messageType === "call") {
                // 正则表达式匹配 "通话时长 " 后面的数字和单位 (秒/分钟)
                const match = item.content.match(/^通话时长\s*(.*)$/);
                let prefix = "通话时长 ";
                let timePart = "";

                if (match && match[1]) {
                  timePart = match[1]; // 获取时间部分，如 "5 秒"
                } else {
                  // 如果不匹配，则整个内容作为前缀（异常情况）
                  prefix = item.content;
                }

                return (
                  <p
                    key={
                      item.id + "-system-call-" + new Date(item.createdAt).getTime()
                    }
                    className="text-center text-[10px] text-gray-400" // 默认灰色
                  >
                    {prefix}
                    {timePart && <span className="text-blue-500">{timePart}</span>}
                  </p>
                );
              } 
              // 然后判断是否是其他类型的系统消息
              else if (item.messageSendType === 0) {
                return (
                  <p
                    key={
                      item.id + "-system-" + new Date(item.createdAt).getTime()
                    }
                    className="text-center text-[10px] text-gray-400" // 保持灰色
                  >
                    {item.content}
                  </p>
                );
              }
              // 最后是用户发送的消息，通过ChatItem渲染
              else {
                return (
                  <ChatItem
                    key={item.id + "-" + new Date(item.createdAt).getTime()}
                    isMe={item.isme}
                    message={item.content}
                    avatar={item.avatar}
                    messagetype={item.messageType}
                    isGroupChat={type === "group"}
                    groupUserName={item.name}
                    userName={item.name}
                    messageId={item.messageId}
                    onRecallMessage={item.isme ? handleRecallMessage : undefined}
                    messageStatus={item.messageStatus}
                    // 传递主题相关的样式
                    customStyle={{
                      myMessageBg: themeSettings?.myMessageBg,
                      friendMessageBg: themeSettings?.friendMessageBg,
                      messageTextColor: themeSettings?.messageTextColor,
                      fontFamily: themeSettings?.fontFamily
                    }}
                  ></ChatItem>
                );
              }
            })}
          </ul>
        </SlideList>
      </div>
      <SlideMove
        changewidth={false}
        elRef={elRef}
        sideRef={sideRef}
        maxHeight={200}
        minHeight={100}
        style={"w-[100%] h-[30%] items-end"}
      >
        <div className="h-[98.5%] w-full border-t-2 px-3 cursor-auto relative box-border">
          <div className="h-6 flex justify-between items-center">
            <div>
              <EmojiPicker onSelect={handleEmojiSelect} />
              <HistoryOutlined className="mr-2 cursor-pointer" onClick={openChatHistory} title="查看完整聊天记录" />
              <SkinOutlined className="mr-2 cursor-pointer" onClick={openThemeSettings} title="更换聊天主题" />
            </div>
            {type === "friend" && (
              <div>
                <PhoneOutlined className="mr-2" onClick={startVoiceCall} style={{ cursor: "pointer" }} />
              </div>
            )}
          </div>
          <TextArea
            value={content}
            onChange={e => setcontent(e.target.value)}
            placeholder="说点什么吧"
            autoSize={{ minRows: 3, maxRows: 3 }}
            className="border-0 focus:shadow-none"
            onPressEnter={e => {
              if (e.shiftKey) {
                // Shift+Enter 换行，不做处理
              } else {
                e.preventDefault(); // 阻止默认的换行
                handelSendMessage();
              }
            }}
          />
          <Button
            type="primary"
            size={"small"}
            className="absolute right-3 bottom-2"
            onClick={handelSendMessage}
            disabled={!content.trim()}
          >
            发送
          </Button>
        </div>
      </SlideMove>
      {voiceCallVisible && opponentInfo && (
        <VoiceCall
          visible={voiceCallVisible}
          onClose={closeVoiceCall} // This calls body.tsx#closeVoiceCall -> body.tsx#handleCallEnded
          friendId={opponentInfo.id}
          friendName={opponentInfo.name}
          friendAvatar={opponentInfo.avatar}
          isIncoming={incomingCall}
        />
      )}
      
      {/* 聊天历史记录弹框 */}
      {historyVisible && params.contactId && (
        <ChatHistory
          visible={historyVisible}
          onClose={closeChatHistory}
          chatId={Number(params.contactId.split("-")[1])}
          chatType={type as "friend" | "group"}
          chatName={opponentInfo?.name || (type === "friend" ? "好友" : "群组")}
        />
      )}

      {/* 主题设置抽屉 */}
      {params.contactId && (
        <ThemeSelector
          visible={themeVisible}
          onClose={closeThemeSettings}
          userId={userId}
          chatId={params.contactId}
          onThemeChange={handleThemeChange}
        />
      )}
    </div>
  );
};

export default MessageBody;
